#include "jsonfile.h"
#include <QPointF>
#include <QDebug>

JsonFile::JsonFile()
{
//    mFile = nullptr;

}

//bool JsonFile::setJsonFilePath(QString path)
//{
//    mFile = new QFile(path);
//    return true;
//}

bool JsonFile::creatJsonFile(QString path, const QVector<QVector<QPointF>>& vec)
{
    if(vec.isEmpty()){
        qDebug()<<"vec is null.";
        return true;
    }

    int len = vec.size();
    QJsonObject jsonSrc;
    QJsonArray pts;
    for(int i = 0; i< len; i++){
        int len1 = vec[i].size();
        QJsonArray pt0;
        for(int j = 0; j< len1; j++){
            QJsonArray pt1;
            pt1.append(vec[i][j].x());
            pt1.append(vec[i][j].y());
            pt0.append(pt1);
        }

        pts.append(pt0);
    }

    jsonSrc.insert("VirtualWalls",QJsonValue(pts));

    // qDebug()<<"json:"<<jsonSrc;


    QJsonDocument document;
    document.setObject(jsonSrc);
    QByteArray byteArray = document.toJson(QJsonDocument::Compact);
    QFile file1(path);
    if(!file1.open(QIODevice::WriteOnly))
    {
        qDebug() << "write json file failed";
    }
    file1.write(byteArray);
    file1.close();
    return true;

}

bool JsonFile::readJsonFromFile(const QString fileName, QJsonObject &obj)
{
    QFile* file = new QFile(fileName);

    if(!file->open(QIODevice::ReadOnly|QIODevice::WriteOnly))
    {
        qDebug()<<"read json file fail!";
        return false;
    }

    bool ret = false;
    QByteArray ba=file->readAll();

    QJsonParseError jsonError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(ba,&jsonError);
    if (!jsonDoc.isNull() && (jsonError.error == QJsonParseError::NoError)){
        QJsonObject json = QJsonObject(jsonDoc.object());
        obj = json;
        ret = true;
    }else{
        qDebug()<<"jsonDoc to JsonObj is error";
        ret = false;
    }

    if(file->isOpen()){
        file->close();
    }

    if(file)
        delete file;
    return true;
}
